---
layout: default
title: Search
---

<h2>Search: <span id="search-page-query"></span></h2>
<div id="search-page-results"></div>

<!-- html template -->
<template id="search-page-result-template">
  <div class="search-page-result">
    <h4>
      <span class="search-page-result-type"></span>
      <span class="search-page-result-title"></span>
    </h4>
    <p class="search-page-result-body"></p>
  </div>
</template>
<script>
  document.addEventListener("DOMContentLoaded", function() {
    var searchQueryMatch = window.location.href.match(/\?query=(.*)/)
    var searchQuery, searchResults
    if (!searchQueryMatch) {
      renderResults("(no query)", [])
    } else {
      searchQuery = decodeURIComponent(searchQueryMatch[1])
      index.search({query: searchQuery, hitsPerPage: 1000}, function(err, content) {
        renderResults(searchQuery, content.hits)
      })
    }

    function renderResults(query, results) {
      var querySpan = document.getElementById('search-page-query')
      querySpan.innerText = '"' + decodeURIComponent(query) + '"'

      var resultsContainer = document.getElementById("search-page-results")
      var resultsTemplate = document.getElementById("search-page-result-template")

      function writeToTemplate(header, body, resultType) {
        resultsTemplate
          .content
          .querySelector(".search-page-result-title")
          .innerHTML = header
        resultsTemplate
          .content
          .querySelector(".search-page-result-body")
          .innerHTML = body

        var resultEl = document.importNode(resultsTemplate.content, true);
        resultsContainer.appendChild(resultEl)
      }

      if (results.length == 0) {
        writeToTemplate("No Results", "")
      } else {
        results.forEach(function(result) {
          var resultPath
          if (result.anchor) {
            resultPath = result.url + "#" + result.anchor
          } else {
            resultPath = result.url
          }

          var resultHeader = [result.section || "API", result.title].concat(result.headings).join(" > ")

          var header = "<a href='" + resultPath + "'>" + resultHeader + '</a>'

          var resultBody = result.rubydoc_url ? "API Docs for " + result.title : result._highlightResult.html.value
          writeToTemplate(header, resultBody)
        })
      }
    }
  })
</script>
